import { cutPostion, getMapBounds } from './utils'

/**
 * 地图点击
 * @param {LatLng} event 经纬度实例对象 event 只有经纬度, 没有实际中文坐标
 */
async function clickListenerHandler (event) {
  // 限定地图上的标记只有一个 link: https://lbs.qq.com/webDemoCenter/javascriptV2/marker/addOneMarker

  // api link: https://lbs.qq.com/javascript_v2/doc/latlng.html
  const lat = cutPostion(event.latLng.getLat())
  const lng = cutPostion(event.latLng.getLng())

  try {
    const result = await this.trasnformPosition(lat, lng)

    if (!event.poi && this.limitPOI) return

    // result 会包含一些和formModel中并不存在的属性，不希望动态挂载到 formModel
    Object.keys(this.formModel).forEach(key => {
      this.formModel[key] = result[key]
    })

    const {address, location} = result

    const preClickPoint = this.markerLayer.getGeometries().find(item => item.properties.pointType === 'click')

    if (preClickPoint) {
      this.markerLayer.remove([preClickPoint.id])
    }

    this.infoWindow.close()

    this.markerLayer.add([
      {
        position: new TMap.LatLng(lat, lng),
        styleId: 'blue',
        properties: {
          title: event.poi ? event.poi.name : '',
          address,
          location,
          uuid: 30,
          pointType: 'click'
        }
      }
    ])

    // 直接展示信息窗口
    if (!this.limitPOI) {
      const title = event.poi ? event.poi.name : ''
      openInfoWindow(this, lat, lng, title, address)
    }
  } catch (e) {
    console.log(e)
  }
}

/**
 * 实时更新经纬度-跟随鼠标
 */
function mouseMoveHandler (event) {
  if (!this.mousemovePosition) return

  let lat = cutPostion(event.latLng.getLat())
  let lng = cutPostion(event.latLng.getLng())

  let position = new TMap.LatLng(lat, lng)

  this.multiLabel.setGeometries([
    {
      styleId: 'label',
      position,
      content: `${lat}, ${lng}`
    }
  ])

  if (!this.isContainesPoint(lat, lng)) {
    this.multiLabel.setGeometries([])
  }
}

/**
 * 以下情况会导致边界更新
 * 1、地图缩放
 * 2、地图拖拽
 * 3、改变视角
 */
function updateBoundsHandler () {
  this.mapBounds = getMapBounds(this.map)
}

function showMarkerMessageHandler (event) {
  const length = Object.keys(event.geometry.properties).length
  if (!length) return

  const {title = '', address = '', uuid} = event.geometry.properties
  // 个别情况 location会不存在，做一个容错处理
  const location = event.geometry.properties.location || {}
  const {lat = '', lng = ''} = location

  openInfoWindow(this, lat, lng, title, address)

  const currentMarker = this.searchMarkerList.find(item => item.uuid === uuid)

  if (currentMarker) {
    const {ad_info: {province, city, district, adcode}} = currentMarker

    this.formModel = Object.assign(this.formModel, {
      province,
      city,
      district,
      lat,
      lng,
      addr: address,
      adcode
    })
  }
}

function openInfoWindow(instance, lat, lng, title, address) {
  const content = `
  <div>
    <p><span style="color: #000; font-weight: 700;display: ${title ? 'inline-block' : 'none'}">名称:</span> ${title}</p>
    <p><span style="color: #000; font-weight: 700;">地址:</span> ${address}</p>
    <p><span style="color: #000; font-weight: 700;">纬度:</span>${lat} <span style="color: #000; font-weight: 700;">经度:</span>${lng}</p>
  </div>
`

  instance.infoWindow.open()
  // 设置信息窗口的坐标
  instance.infoWindow.setPosition(new TMap.LatLng(lat, lng))
  // 设置信息窗口的内容
  instance.infoWindow.setContent(content)
}

/**
 * 所有事件绑定
 * @param {VueComponent} instance Vue实例对象
 * @link https://lbs.qq.com/webApi/javascriptGL/glDoc/docIndexMap
 */
export const bindEventListener = (instance) => {
  instance.map.on('click', event => clickListenerHandler.call(instance, event))

  instance.map.on('mousemove', event => mouseMoveHandler.call(instance, event))

  instance.map.on('bounds_changed', event => updateBoundsHandler.call(instance, event))

  instance.markerLayer.on('click', event => showMarkerMessageHandler.call(instance, event), false)
}

export const removeEventListener = (instance) => {
  if (instance.map) {
    console.log('地图组件销毁')
    instance.infoWindow && instance.infoWindow.destroy()
    instance.markerLayer.off('click', showMarkerMessageHandler)
    instance.map.off('click', clickListenerHandler)
    instance.map.off('mousemove', mouseMoveHandler)
    instance.map.off('bounds_changed', updateBoundsHandler)

    // 销毁实例对象
    instance.map.destroy()
  }
}
